// init
$(document).ready(onloadmediasearch);

/**
 * init
 */
function onloadmediasearch() {
    $("#mediaSearchButton").click(searchRequest);
    $("#mediaSearchTextField").keypress(function(event) {
        // jQuery.Event
        if (event.charCode == 13) // enter
            searchRequest();
    });
}

/**
 * click sur ajout rapide
 */
function click_addMovie_fast(e) {
    
    var parent_tr = $(this).parent().parent();
    var options = parent_tr.data("options");
    console.debug("options: %o", options);
    console.debug(options.api_id);
    console.debug(options.api_name);

    var addIcon = $('#add-movie-img-' + options.js_index).attr('src');
    if (addIcon != '/mediaglobe/images/icons/add.png')
        return;

     var url = readCookie("baseurl") + "/media/addmovie";
     url += "?js_index=" + options.js_index;
     
     if (options.movieIdInDB == -1) {
         url += "&api_id=" + options.api_id;
         url += "&api_name=" + options.api_name;
     }
     else {
         url += "&movieIdInDB=" + options.movieIdInDB;
     }
    
     $('#add-movie-img-' + options.js_index).attr('src', '/mediaglobe/images/icons/wait-1.gif');
     
     $.ajax({
         type : "GET",
         url : url,
         success : function(msg) {
             console.debug("res addmovie %o", msg);
             if (msg.success) {
                 $('#add-movie-img-' + options.js_index).attr('src', '/mediaglobe/images/icons/green-notch.png');
             }
             else {
                 $('#add-movie-img-' + options.js_index).attr('src', '/mediaglobe/images/icons/add.png');
             }
         }
     });
}

/**
 * click sur ajout de film (dans la description). prends en compte les infos fournie.
 */
function click_addMovie_advanced(e) {

    // TODO
    
}

/**
 * Details/Description Movie
 * 
 * @param index
 */
function click_showDescription(e) {
    
    var parent_tr = $(this).parent().parent();
    var options = parent_tr.data("options");
    // var options = JSON.parse(parent_tr.data("options"));
    var index = options.js_index;
    var api_id = options.api_id;
    
    var desc_tr = $('#movie-tr-' + index);
    
    if (desc_tr.is(':visible')) {
        
        $('td div', desc_tr).hide(200, function() {
            desc_tr.hide();
            $('#movie-img-' + index).attr('src', '/mediaglobe/images/icons/double-chevron-down.png');
        });
        // $('td div', desc_tr).hide('blind', {}, 200, function() {
        //            
        // desc_tr.hide();
        // $('td div', desc_tr).hide();
        // // desc_tr.attr('src',
        // // '/mediaglobe/images/icons/double-chevron-down.png');
        // // $(this).remove();
        // });
        return;
    }
    else if (options.hasOwnProperty('loaded')) {
        
        $('#movie-tr-' + index).show();
        
        // $('#movie-tr-' + index + ' td div').show('blind', {}, 200);
        $('td div', desc_tr).show(500);
        
        $('#movie-img-' + index).attr('src', '/mediaglobe/images/icons/double-chevron-up.png');
        
        return;
    }
    
    var html_desc = "";
    html_desc += '<div style="display:none;">';
    html_desc += "<div>";
    html_desc += "<img src='' style='width:30%; display:inline-block; padding-right: 10px'/>";
    html_desc += "<div class='desc-main'>";
    html_desc += "<h3>Synopsis</h3>";
    html_desc += '<p class="plot"></p>';
    
    html_desc += "<div class='movie-add-box-container'>";
    html_desc += "<div id='movie-add-box-" + index + "' class='movie-add-box'>";
    html_desc += "</div>";
    
    html_desc += "</div>";
    html_desc += "</div>";
    html_desc += "</div>";
    html_desc += "</div>";
    
    $('#movie-td-' + index).append(html_desc);
    
    $('#movie-img-' + index).attr('src', '/mediaglobe/images/icons/wait-1.gif');
    
    // FIXME gerer le nom de l'api en plus de l'id
    // var url = readCookie("baseurl") + "/media/getdetails?api_id="
    // + $('button', desc_tr.prev()).data('options').api_id;
    var url = readCookie("baseurl") + "/media/getdetails/api_id/" + api_id;
    // 154530
    
    $.ajax({
        type : "GET",
        url : url,
        success : function(msg) {
            
            $('img', '#movie-tr-' + index + ' td div').attr('src', msg.poster);
            
            if (msg.plot == "")
                $('.plot', desc_tr).html("Non disponible...");
            else
                $('.plot', desc_tr).html(msg.plot);
            
            $('#movie-tr-' + index).show();
            
            // $('#movie-tr-' + index + ' td div').show('blind', {}, 200);
            $('td div', desc_tr).show(500);
            
            $('#movie-img-' + index).attr('src', '/mediaglobe/images/icons/double-chevron-up.png');
            
            html_addBox = getHTML_addBox();
            $('#movie-add-box-' + index).append(html_addBox);
            
            options.loaded = true;
            parent_tr.data("options", options);
        }
    });
    
}

function getHTML_addBox() {
    var html_addBox = "";
    html_addBox += "<h3>Ajout avancé</h3>";
    
    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Format</label>";
    html_addBox += "<select style='width:100px'>";
    html_addBox += "<option value='0'>-</option>";
    html_addBox += "<option value='1'>Blueray</option>";
    html_addBox += "<option value='2'>DVD</option>";
    html_addBox += "<option value='3'>Virtuel</option>";
    html_addBox += "</select>";
    html_addBox += "</div>";
    
    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Qualité</label><input type='text' style='width:100px'/>";
    html_addBox += "</div>";
    
    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Langues</label>";
    html_addBox += "<input type='checkbox' name='lang' value='fr'>fr";
    html_addBox += "<input type='checkbox' name='lang' value='en'>en";
    html_addBox += "<input type='checkbox' name='lang' value='other'>Autre";
    html_addBox += "</div>";
    
    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Sous-titres</label>";
    html_addBox += "<input type='checkbox' name='ss' value='fr'>fr";
    html_addBox += "<input type='checkbox' name='ss' value='en'>en";
    html_addBox += "<input type='checkbox' name='ss' value='other'>Autre";
    html_addBox += "</div>";
    
    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Vu</label>";
    html_addBox += "<input type='radio' name='seen'>oui";
    html_addBox += "<input type='radio' name='seen'>non";
    html_addBox += "</div>";

    html_addBox += "<div style='text-align:right'>";
    html_addBox += "<label class='bold'>Visible par vos amis</label>";
    html_addBox += "<input type='radio' name='visible'>oui";
    html_addBox += "<input type='radio' name='visible'>non";
    html_addBox += "</div>";
    
    html_addBox += "<input type='button' value='Ajouter'/>";
    
    return html_addBox;
}

/**
 * ajoute un film dans la table html
 * 
 * @param movie
 * @param index
 */
function getHTML_movie(movie, index) {
    
    // Date
    var strDate = "???";
    if (movie.year && movie.year != "") {
        try {
            var date = new Date(movie.year);
            strDate = date.format('yyyy');
        }
        catch (err) {
            
        }
    }
    
//    console.debug('%o', movie);
    
    var data_options = '{';
    data_options += '"js_index":' + index;
    data_options += ',"api_id":' + movie.api_idMovie;
    data_options += ',"api_name":"' + movie.api_name + '"';
    data_options += ',"movieIdInDB":' + movie.movieIdInDB;
    data_options += '}';
    
    var html_movie = "";
    
    /* tr de base */
    html_movie += "<tr data-options='" + data_options + "'>";
    html_movie += "<td><img class='show-desc-img button' id='movie-img-" + index + "' class='button' src='/mediaglobe/images/icons/double-chevron-down.png'/></td>";
    html_movie += '<td>' + movie.title + '</td>';
    html_movie += '<td>' + strDate + '</td>';
    // html_movie += "<td><button class='addButton' data-options='" +
    // data_options
    // + "'>Ajouter</button></td>";
    // html_movie += "<td><button
    // class='add-movie-button'>Ajouter</button></td>";
    html_movie += "<td><img id='add-movie-img-" + index + "' class='add-movie-img button' src='/mediaglobe/images/icons/add.png'></td>";
    html_movie += '</tr>';
    
    /* tr de description */
    html_movie += "<tr id='movie-tr-" + index + "' style='display:none;'>";
    html_movie += "<td id='movie-td-" + index + "' style='background-color:#eee;' colspan='4'></td>";
    html_movie += '</tr>';
    
    return html_movie;
    
    // $("#resTable > table tr:last").after(table);
}

/**
 * Recherche de film
 */
function searchRequest() {
    searchSortedRequest('year', 'desc');
}

var storedRequest = null;
var storedMovies = null;

/**
 * Recherche de film
 * 
 * @param sort
 *            "title" ou "year"
 * @param order
 *            "desc" ou "asc"
 */
function searchSortedRequest(sort, order) {
    
    // FIXME: gif wait
    // $("#resTable").text("Recherche...");
    $("#resTable").empty();
    $("#resTable").append("<img src='/mediaglobe/images/icons/wait-2.gif'/>");
    
    // champs de recherche
    var searchRequest = $("#mediaSearchTextField").val();
    
    // Si les films sont déjà stockés
    if (storedRequest == searchRequest) {
        showMovies(storedMovies, sort, order);
        return;
    }
    
    // Si les films ne sont pas stockés
    
    var searchUrl = readCookie("baseurl") + "/media/search";
    searchUrl += "/title/" + searchRequest;
    searchUrl += "/sort/" + sort;
    searchUrl += "/order/" + order;
    
    $.ajax({
        type : "GET",
        timeout : 5000,
        url : searchUrl,
        success : function(msg) {
            
            storedRequest = searchRequest;
            storedMovies = msg;
            
            if (msg.length != 0) {
                showMovies(msg, sort, order);
            }
            else {
                $("#resTable").text("Aucun resultat");
            }
        },
        error : function(x, t, m) {
            if (t === "timeout")
                alert("mediasearch: timeout");
            else {
                console.debug("%o" + t + m, x);
                // alert("Erreur lors de la recherche de média");
            }
        }
    });
}

/**
 * 
 * @param movies
 *            liste
 * @param sort
 *            "title" ou "year"
 * @param order
 *            "desc" ou "asc"
 */
function showMovies(movies, sort, order) {
    
    // SORT
    movies = sortMovies(movies, sort, order);
    
//    for (var abc = 0 ; abc < movies.length ; abc++) {
//        console.debug('%o', movies[abc]);
//    }
    
    var table = "";
    
    // Gestion des headers avec le tri
    var sortTitle = "<div class='sort-container'>";
    sortTitle += "<img class='button sort' src='/mediaglobe/images/icons/arrow-up.png' onclick='searchSortedRequest(\"title\", \"asc\")'/>";
    sortTitle += "<img class='button sort' src='/mediaglobe/images/icons/arrow-down.png' onclick='searchSortedRequest(\"title\", \"desc\")'/>";
    sortTitle += "</div>";
    var sortYear = "<div class='sort-container'>";
    sortYear += "<img class='button sort' src='/mediaglobe/images/icons/arrow-up.png' onclick='searchSortedRequest(\"year\", \"asc\")'/>";
    sortYear += "<img class='button sort' src='/mediaglobe/images/icons/arrow-down.png' onclick='searchSortedRequest(\"year\", \"desc\")'/>";
    sortYear += "</div>";
    
    // Ajout des headers
    table += "<table style='width:100%;'><tr>";
    table += "<th>Détails</th>";
    table += "<th><label>Title</label>" + sortTitle + "</th>";
    table += "<th>Année" + sortYear + "</th>";
    table += "<th>Ajout rapide</th>";
    table += "</tr>";
    for ( var i = 0; i < movies.length; ++i)
        table += getHTML_movie(movies[i], i);
    table += '</table>';
    
    $("#resTable").html(table);
    
    // $("#resTable > table tr").tooltip({items: "tr", content :
    // showTooltipDesc});
    
    $(".show-desc-img").click(click_showDescription);
    $(".add-movie-img").click(click_addMovie_fast);
}

/**
 * Tri
 * 
 * @param movies
 * @param sort
 * @param order
 * @returns {Array}
 */
function sortMovies(movies, sort, order) {
    
    var moviesIndexes = new Array(); // contient des Array(year, index in
    // movies)
    var moviesSorted = new Array();
    
    for ( var i = 0; i < movies.length; i++) {
        if (sort == 'year')
            moviesIndexes[i] = new Array(movies[i].year, i);
        else
            moviesIndexes[i] = new Array(movies[i].title, i);
    }
    
    orderValue = 1;
    if (order == 'desc')
        orderValue = -1;
    
    moviesIndexes.sort(function(a, b) {
        var y_a = a[0];
        var y_b = b[0];
        
        // null : fin de liste
        if (!y_a)
            return -1 * orderValue;
        if (!y_b)
            return orderValue;
        
        if (y_a < y_b)
            return -1 * orderValue;
        if (y_a > y_b)
            return orderValue;
        return 0;
    });
    
    for ( var i = 0; i < moviesIndexes.length; i++) {
        moviesSorted[i] = movies[moviesIndexes[i][1]];
    }
    return moviesSorted;
}

